import logging
import os
import sys

project_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(project_path)
from collections import defaultdict

from apscheduler.schedulers.blocking import BlockingScheduler

from config import REDIS_DATABASE_KEY
from enumobjects.general_enum import YesOrNoEnum
from libs.redis_wrapper import RedisWrapper
from models.annotation_models.annotation_model import Annotation
from models.data_models.data_model import Data
from models.project_models.project_model import Project
from utils.common_util import CommonUtil
from utils.db_util import CreateEngine

engine = CreateEngine()
db_session = engine.get_engine(method="label")
def data_rescan():
    projects = db_session.query(Project).filter(Project.is_delete == YesOrNoEnum.NO.value,
                                                                Project.create_time >= CommonUtil.get_timestamp() - (
                                                                            7 * 24 * 60 * 60)).all()
    project_ids = [project.project_id for project in projects]
    if not projects:
        return
    annotated_subquery = db_session.query(Annotation.data_id).distinct()
    # 主查询: 查找在指定 project_id 中未标注的图片
    unlabeled_images = db_session.query(Data.data_id, Data.project_id).filter(
        Data.project_id.in_(project_ids),  # 筛选指定的 project_ids
        ~Data.data_id.in_(annotated_subquery)  # 筛选未标注的图片
    ).all()
    images_by_project = defaultdict(list)
    for data_id, project_id in unlabeled_images:
        images_by_project[project_id].append(data_id)
    for project in projects:
        logging.info(project.project_id,images_by_project[project.project_id])
        if images_by_project[project.project_id] is not None:
            project.state = 0
    with RedisWrapper.r.pipeline() as pipe:
        for project_id, data_ids in images_by_project.items():
            for data_id in data_ids:
                pipe.lpush(REDIS_DATABASE_KEY+str(project_id), data_id)
        pipe.execute()


scheduler = BlockingScheduler()
# 添加定时任务，每 10 分钟执行一次
get_method = lambda: data_rescan()
scheduler.add_job(get_method, 'interval', seconds=5)

try:
    scheduler.start()  # 启动调度器
except (KeyboardInterrupt, SystemExit):
    pass